<template>
  <div class="oe-carte-management" style="margin-top: 20px;" v-loading="loading">
    <topTip :title="title" :showBack="showBack"></topTip>
    <div class="carte-management-list clearfix">
      <div class="carte-three fl">
        <a-button @click="getZtree_old" type="primary" html-type="submit"  v-if="operationList.includes('edit/del')">查看默认菜单</a-button>
        <a-tree
          :showLine="true"
          :treeData="treeData"
          :loadData="onLoadData"
          @select="onSelect"
          :defaultSelectedKeys="[ztreeId]"
          show-icon
        >
          <a-icon slot="smile" type="form" @click="getIcon" />
        </a-tree>
      </div>
      <div class="carte-list-table fr">
        <div class="oe-list-search">
          <span class="oe-list-text">菜单名称：</span>
          <span class="oe-list-input">
            <a-input placeholder="输入菜单名称" v-model="menuKey" class="oe-list-input-text" />
          </span>
          <span class="oe-list-text">操作名称：</span>
          <span class="oe-list-input">
            <a-input placeholder="输入操作名称" v-model="operationKey" class="oe-list-input-text" />
          </span>
          <span class="oe-list-btns">
            <a-button type="primary" @click.stop="getOperation">查询</a-button>
          </span>
        </div>
        <a-table
          :columns="columns"
          :dataSource="data"
          :pagination="pagination"
          class="oe-list-table"
        >
          <template slot="operation" slot-scope="text, record">
            <span
              :value="role.Id"
              v-for="(role,index) in record.RoleNames"
              :key="index"
              class="roleSpan"
            >
              {{role.RoleName}}
              <span
                v-if="operationList.includes('edit/del')"
                style="color: red;cursor: pointer;"
                title="删除"
                @click="getSave(record.Id,role.Id)"
              >x</span>
            </span>
          </template>
          <template slot="operationRead" slot-scope="text, record">
            <span
              :value="role.Id"
              v-for="role in record.IsReadRoleNames"
              :key="role.Id"
              class="roleSpan"
            >
              {{role.RoleName}}
              <span
                v-if="operationList.includes('edit/del')"
                style="color: red;cursor: pointer;"
                title="删除"
                @click="getSave(record.Id,role.Id)"
              >x</span>
            </span>
          </template>
        </a-table>
      </div>
    </div>
    <a-modal
      title="编辑菜单"
      :visible="editMenu"
      :confirmLoading="confirmLoading"
      @cancel="addCancel"
    >
      <div class="oe-select">
        <a-form-model v-bind="layout">
          <a-form-model-item label="菜单名称" prop="menuName" ref="menuName">
            <a-input v-model="menuName" placeholder="请输入菜单名称" />
          </a-form-model-item>
        </a-form-model>
      </div>
      <template slot="footer">
        <a-button @click="addSure" type="primary" html-type="submit">确定</a-button>
        <a-button @click.stop="addCancel">取消</a-button>
      </template>
    </a-modal>
    <a-modal
      title="系统默认菜单"
      class="oe-studentAdd"
      :visible="lookOldMenu"
      :confirmLoading="confirmLoading"
      @cancel="addCancel"
      destroyOnClose
    >
      <div class="oe-select">
        <a-tree
          :showLine="true"
          :treeData="treeData_old"
          :loadData="onLoadData_old"
          @select="onSelects_old"
          :defaultSelectedKeys="[ztreeId]"
          show-icon
        ></a-tree>
      </div>
      <template slot="footer">
        <a-button @click="saveOldMenu" type="primary" html-type="submit" v-if="operationList.includes('edit/del')">使用默认菜单</a-button>
        <a-button @click.stop="addCancel">取消</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import topTip from '@/components/top-tip/index.vue';
import GetOperationList from '@/lib/mixin/methods.js';
export default {
  components: {
    topTip
  },
  mixins: [GetOperationList],
  props: {
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      menuName: '',
      editMenu: false,
      lookOldMenu: false,
      showBack: false,
      setIcon: false,
      title: [{ text: '菜单管理' }],
      name: '',
      all: false,
      noAll: false,
      allLook: false,
      isShow: false,
      pagination: {
        pageSizeOptions: ['10', '20', '50', '100', '1000'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal(total) {
          return `共 ${total} 条`;
        },
        onShowSizeChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
          this.getOperation();
        },
        onChange: (current, pageSize) => {
          this.pagination.current = current;
          this.pagination.pageSize = pageSize;
          this.getOperation();
        },
        buildOptionText(props) {
          return props.value + '条/页';
        },
        current: 1,
        pageSize: 10
      },
      data: [],
      columns: [
        { title: '序号', dataIndex: 'key', width: '8%' },
        { title: '菜单名称 ', dataIndex: 'MenuName', width: '15%' },
        { title: '操作名称 ', dataIndex: 'Name', width: '15%' },
        { title: '可管理角色', dataIndex: 'operation', width: '32%', scopedSlots: { customRender: 'operation' } },
        {
          title: '仅查看角色',
          dataIndex: 'operationRead',
          width: '30%',
          scopedSlots: { customRender: 'operationRead' }
        }
      ],
      operationKey: '',
      menuKey: '',
      loading: false,
      treeData: [],
      plainOptions: ['只读', '读写'],
      ztreeId: '',
      treeData_old: [],
      ztreeId_old: '',
      childList: [],
      cahceZtreeId: '',
      cahceZtreeId_old: '',
      operationList: [],
      // 、操作list
      IsOpList: [],
      layout: {
        labelCol: { span: 4 },
        wrapperCol: { span: 18 },
      },
    };
  },
  computed: {},
  mounted() {
    this.getOpeartion();
  },
  methods: {
    // 获取页面操作
    getOpeartion() {
      this.loading = true;
      this.GetOperationList().then((rst) => {
        this.loading = false;
        this.operationList = [];
        this.IsOpList = [];
        if (rst.code === 1) {
          if (rst.list.length) {
            rst.list.forEach((item) => {
              if (item.IsWrite) {
                this.operationList.push(item.Name);
              }
            });
            this.IsOpList = rst.list;
            // this.operationList = rst.list;
          }
          this.getZtree();
        } else {
          this.$message.error(rst.msg);
        }
      });
    },
    // 判断是否是只读
    getIsWrite(type) {
      type = 'add/edit/del:menu';
      let index = this.IsOpList.findIndex((el) => {
        return el.Name === type;
      });
      if (index > -1) {
        if (this.IsOpList[index].IsRead && !this.IsOpList[index].IsWrite) {
          this.$message.info('您没有该操作权限！');
          return false;
        } else {
          return true;
        }
      }
    },
    onSelect(selectedKeys, info) {
      setTimeout(() => {
        if (this.setIcon) {
          this.ztreeId = selectedKeys[0];
          this.$http
            .post('/api/SchoolManager/rolemenu/getSchoolMenu', {
              menuId: this.ztreeId //菜单Id
            })
            .then((res) => {
              this.setIcon = false;
              this.loading = false;
              this.editMenu = true;
              this.menuName = res;
            });
        } else {
          this.onSelects(selectedKeys, info);
        }
        return false;
      }, 300);
    },
    addSure() {
      this.$http
        .post('/api/SchoolManager/rolemenu/saveSchoolMenu', {
          menuId: this.ztreeId, //菜单Id
          menuName: this.menuName
        })
        .then((res) => {
          this.loading = false;
          if (res.code > 0) {
            this.$message.success(res.msg);
            this.editMenu = false;
            this.$router.go(0);
          } else {
            this.$message.error(res.msg);
          }
        });
    },
    addCancel() {
      this.editMenu = false;
      this.lookOldMenu = false;
      this.ztreeId_old = '';
      this.treeData_old = [];
      this.cahceZtreeId_old = '';
      return false;
    },
    onSelects(selectedKeys, info) {
      console.log('selectedKeys', selectedKeys);
      console.log('info', info);
      this.pagination.current = 1;
      this.pagination.pageSize = 10;
      if (selectedKeys.length) {
        this.cahceZtreeId = selectedKeys[0];
      }
      this.ztreeId = this.cahceZtreeId;
      this.getOperation();
    },
    getIcon() {
      this.setIcon = true;
    },
    onOperation(data, type) {
      if (type == 1) {
        if (data.IsWrite) {
          data.IsRead = false;
        }
      } else {
        if (data.IsRead) {
          data.IsWrite = false;
        }
      }
      this.getSave(data);
    },
    getSave(operationId, roleId) {
      this.$confirm({
        title: '提示',
        content: '确定要删除此操作的该角色吗？',
        centered: true,
        onOk: () => {
          this.loading = true;
          this.$http
            .post('/api/SchoolManager/rolemenu/save', {
              roleId: roleId, //角色Id
              // menuId: this.ztreeId, //菜单Id
              operationId: operationId, //操作Id
              isDelRole: true,
              isRead: false, //是否只读
              isWrite: false //是否读写
            })
            .then((res) => {
              this.loading = false;
              if (res.code > 0) {
                this.$message.success(res.msg);
                this.getOperation();
              } else {
                this.$message.error(res.msg);
              }
            });
        }
      });
    },
    getZtree() {
      this.loading = true;
      this.$http.post('/api/SchoolManager/rolemenu/ztree').then((res) => {
        this.treeData = this.getZtreeData(res);
        this.ztreeId = res[0].id;
        this.getOperation();
      });
    },
    // 重新构造树状图结构
    getZtreeData(data) {
      var ztreeData = [];
      for (let i = 0; i < data.length; i++) {
        let lis = {
          key: data[i].id,
          title: data[i].name,
          isParent: data[i].isParent,
          slots: {
            icon: 'smile'
          }
        };
        if(!data[i].isParent){
          lis.isLeaf = true;
        }
        ztreeData.push(lis);
      }
      return ztreeData;
    },
    // 树状图异步加载
    onLoadData(treeNode) {
      if (treeNode.dataRef.isParent) {
        return this.getZtreeTwo(treeNode.dataRef.key).then((res) => {
          if (treeNode.dataRef.children) {
            return;
          }
          treeNode.dataRef.children = res;
          this.treeData = [...this.treeData];
          return res;
        });
      } else {
        return Promise.resolve();
      }
    },
    saveOldMenu() {
      this.$confirm({
        title: '提示',
        content: '确定要使用系统默认的菜单吗？',
        centered: true,
        onOk: () => {
          this.loading = true;
          this.$http.post('/api/SchoolManager/rolemenu/saveOldMenu').then((res) => {
            this.loading = false;
            if (res.code > 0) {
              this.$message.success(res.msg);
              this.$router.go(0);
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    getZtreeTwo(Id) {
      this.childList = [];
      return this.$http
        .post('/api/SchoolManager/rolemenu/ztree', {
          Id: Id
        })
        .then(this.getZtreeData);
    },
    getOperation() {
      this.loading = true;
      this.$http
        .post('/api/SchoolManager/rolemenu/getMenuOperation', {
          menuKey: this.menuKey,
          operationKey: this.operationKey,
          menuId: this.ztreeId, //菜单id
          pageSize: this.pagination.pageSize,
          page: this.pagination.current
        })
        .then((res) => {
          this.loading = false;
          if (res.code > 0) {
            this.data = res.list;
            for (let i = 0; i < res.list.length; i++) {
              this.data[i].key = i + 1;
            }
          } else {
            this.$message.error(res.msg);
          }
          this.loading = false;
        });
    },
    onSelects_old(selectedKeys, info) {
      if (selectedKeys.length) {
        this.cahceZtreeId_old = selectedKeys[0];
      }
      this.ztreeId_old = this.cahceZtreeId_old;
      return false;
    },
    getZtree_old() {
      this.lookOldMenu = true;
      this.$http.post('/api/SchoolManager/rolemenu/ztree_old').then((res) => {
        this.treeData_old = this.getZtreeData_old(res);
        this.ztreeId_old = res[0].id;
      });
    },
    // 重新构造树状图结构
    getZtreeData_old(data) {
      var ztreeData = [];
      for (let i = 0; i < data.length; i++) {
        let lis = {
          key: data[i].id,
          title: data[i].name,
          isParent: data[i].isParent,
          slots: {
            icon: 'smile'
          }
        };
        if(!data[i].isParent){
          lis.isLeaf = true;
        }
        ztreeData.push(lis);
      }
      return ztreeData;
    },
    // 树状图异步加载
    onLoadData_old(treeNode) {
      if (treeNode.dataRef.isParent) {
        return this.getZtreeTwo_old(treeNode.dataRef.key).then((res) => {
          if (treeNode.dataRef.children) {
            return;
          }
          treeNode.dataRef.children = res;
          this.treeData_old = [...this.treeData_old];
          return res;
        });
      } else {
        return Promise.resolve();
      }
    },
    getZtreeTwo_old(Id) {
      this.childList = [];
      return this.$http
        .post('/api/SchoolManager/rolemenu/ztree_old', {
          Id: Id
        })
        .then(this.getZtreeData_old);
    }
  }
};
</script>
